package com.zsy.interceptor;

import com.zsy.utils.CurrentHolder;
import com.zsy.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-09-12 19:39
 **/
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return true :放行  false：拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头获取token
        String token = request.getHeader("token");
        // 校验token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = claims.get("id", Integer.class);
            log.info("当前用户id:{}", id);
            CurrentHolder.setCurrentUserId(id);
        } catch (Exception e) {
            log.info("解析令牌失败, 返回错误结果");
            // 校验失败给前端返回401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 校验成功放行
        log.info("令牌合法, 放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 资源执行后执行一次
        log.info("执行postHandle.....");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 资源页面渲染
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        // 移除当前用户
        CurrentHolder.remove();
    }
}
